﻿using Autofac;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WCS_Utility.ConstString;
using WCS_Utility.Enums;

namespace WCS_Core.AutoFac
{
    public class AutofacModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;

            #region 带有接口层的服务注入

            var servicesDllFile = Path.Combine(basePath, "WCS_Service.dll");
            var repositoryDllFile = Path.Combine(basePath, "WCS_Repository.dll");

            if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
            {
                var msg = "WCS_Repository.dll和WCS_Service.dll 丢失，因为项目解耦了，所以需要先F6编译，再F5运行，请检查 bin 文件夹，并拷贝。";
                Log.Error(msg);
                return;
            }

            // 获取 Service.dll 程序集服务，并注册
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);
            //支持属性注入依赖重复
            builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces().InstancePerDependency()
                .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).Where(t => t.Name.EndsWith("Service"));

            builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces().SingleInstance().
                PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).Where(t => t.Name.EndsWith("Control"));

            // 获取 Repository.dll 程序集服务，并注册
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            //支持属性注入依赖重复
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces().InstancePerDependency()
                .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).Where(t => t.Name.EndsWith("Repository"));


            #endregion

        }
    }
}
